/*
 * @Author: i@douxuefeng.cn
 * @Date: 2022-04-12 14:36:59
 * @LastEditTime: 2022-04-12 14:40:38
 * @LastEditors: i@douxuefeng.cn
 * @Description:
 * @FilePath: \go-wechat\pay\notify\notify.go
 */
package notify

import (
	"context"
	"net/http"

	"gitee.com/douxuefeng/go-wechat/pay/config"
	"github.com/wechatpay-apiv3/wechatpay-go/core/auth/verifiers"
	"github.com/wechatpay-apiv3/wechatpay-go/core/downloader"
	pay_notify "github.com/wechatpay-apiv3/wechatpay-go/core/notify"
	"github.com/wechatpay-apiv3/wechatpay-go/services/payments"
	"github.com/wechatpay-apiv3/wechatpay-go/utils"
)

type notify struct {
	*config.PayConfig
}

func NewNotify(cfg *config.PayConfig) *notify {
	return &notify{cfg}
}

func (p *notify) GetNotify(r *http.Request) (*payments.Transaction, error) {
	ctx := context.Background()
	mchPrivateKey, err := utils.LoadPrivateKeyWithPath(p.ApiclientKey)
	if err != nil {
		return nil, err
	}
	// 1. 使用 `RegisterDownloaderWithPrivateKey` 注册下载器
	err = downloader.MgrInstance().RegisterDownloaderWithPrivateKey(ctx, mchPrivateKey, p.MchCertificateSerialNumber, p.MchId, p.MchApiV3Key)
	if err != nil {
		return nil, err
	}
	// 2. 获取商户号对应的微信支付平台证书访问器
	certVisitor := downloader.MgrInstance().GetCertificateVisitor(p.MchId)
	// 3. 使用证书访问器初始化 `notify.Handler`
	handler := pay_notify.NewNotifyHandler(p.MchApiV3Key, verifiers.NewSHA256WithRSAVerifier(certVisitor))
	transaction := new(payments.Transaction)
	_, err = handler.ParseNotifyRequest(ctx, r, transaction)
	return transaction, err
}
